package springIOC.IOC_XML.uitl;

import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

@Component
public class ConnectionUtil {
    private ThreadLocal<Connection> local=new ThreadLocal<>();

    private DataSource dataSource;

    public ConnectionUtil(DataSource dataSource){
        this.dataSource=dataSource;
    }

    @Bean(name = "connection")
    public Connection getConnection(){
        Connection con=local.get();
        if(con==null){
            try {
                con=dataSource.getConnection();
                local.set(con);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return con;
    }

}
